//
//  SafeSpecialTypeViewController.m
//  Estate
//
//  Created by wangdongdong on 2017/9/29.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#import "SafeSpecialTypeModel.h"
#import "SafeSpecialTypeCell.h"

#import "SafeSpecialTypeViewController.h"

@interface SafeSpecialTypeViewController ()<UITableViewDelegate, UITableViewDataSource>

// 表格
@property (strong, nonatomic) TPKeyboardAvoidingTableView *tableView;

// 数据源
@property (strong, nonatomic) NSMutableArray *dataMArr;

// 工种类型
@property (strong, nonatomic) NSArray *workTypeArr;
@property (strong, nonatomic) NSArray *workTypeArr2;
// 选择数据
@property (strong, nonatomic) NSMutableArray *selectArr;



@end

@implementation SafeSpecialTypeViewController

// 选择数据
- (NSMutableArray *)selectArr {
    if (!_selectArr) {
        _selectArr = [NSMutableArray array];
    }
    return _selectArr;
}

// 工种类型
- (NSArray *)workTypeArr {
    if (!_workTypeArr) {
        _workTypeArr = @[@"电工", @"电焊工", @"架子工", @"信号工", @"塔机司机", @"起重机司机", @"空压机司机"];
    }
    return _workTypeArr;
}
- (NSArray *)workTypeArr2 {
    if (!_workTypeArr2) {
        _workTypeArr2 = @[@":WORK_TYPE_01", @":WORK_TYPE_02", @":WORK_TYPE_03", @":WORK_TYPE_04", @":WORK_TYPE_05", @":WORK_TYPE_06", @":WORK_TYPE_07"];
    }
    return _workTypeArr2;
}

// 数据源
- (NSMutableArray *)dataMArr {
    
    if (!_dataMArr) {
        _dataMArr = [NSMutableArray array];
        SafeSpecialTypeModel *model = [[SafeSpecialTypeModel alloc] init];
        [_dataMArr addObject:model];
    }
    return _dataMArr;
}

- (TPKeyboardAvoidingTableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 188) style:UITableViewStylePlain];
        _tableView.backgroundColor = UIColorFromRGB(0xf2f2f2);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

        [_tableView registerNib:[UINib nibWithNibName:@"SafeSpecialTypeCell" bundle:nil] forCellReuseIdentifier:@"specialCell"];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];

    // 创建添加btn
    UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRECTS(260, 360, 100, 100)];
    [self.view addSubview:addBtn];
    [addBtn setImage:[UIImage imageNamed:@"add_2"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
}

// 添加通知(暂存/保存检查信息)
- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveSecurityCheckInformation:) name:@"saveSafeCheck" object:nil];
}

// 移除通知(暂存/保存检查信息)
- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"saveSafeCheck" object:nil];
}

// 添加
- (void)submit {
    SafeSpecialTypeModel *model = [[SafeSpecialTypeModel alloc] init];
    [self.dataMArr addObject:model];
    [self.tableView reloadData];
    
    // 滚到指定位置
    [self.tableView layoutIfNeeded];
    NSIndexPath *dayOne = [NSIndexPath indexPathForRow:0 inSection:self.dataMArr.count-1];
    [self.tableView scrollToRowAtIndexPath:dayOne atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - 暂存/保存 安全检查信息
- (void)saveSecurityCheckInformation:(NSNotification *)notification {
    // 接收通知来的信息
    NSDictionary *parameDic = [notification object];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    for (SafeSpecialTypeModel *model in self.dataMArr) {
        // 字段及对应值
        NSDictionary *pragameDic = [NSDictionary dictionary];
        pragameDic = @{
                       @"ID":DEFISNUL([NSUUID UUID].UUIDString),
                       @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                       @"BASIC_RECORD_ID":DEFISNUL(parameDic[@"safeBaseID"]),
                       @"RECORD_USER":DEFISNUL(DEF_PERSISTENT_GET_OBJECT(@"userid")),
                       @"RECORD_TYPE":DEFISNUL(@"SAFE_RECORD_04"),
                       @"RECORD_TITLE":DEFISNUL(parameDic[@"title"]),
                       @"RECORD_NUMBER":DEFISNUL(parameDic[@"recordNumber"]),
                       
                       @"CHECK_NAME":DEFISNUL(model.checkName),
                       @"WORK_TYPE":DEFISNUL(model.workType),
                       @"APPLY_CNT":DEFISNUL(model.applyCnt),
                       @"CHECK_REAL_CNT":DEFISNUL(model.checkRealCnt),
                       @"SOUCE_CHECK_CNT":DEFISNUL(model.sourceCheckCnt),
                       @"EFFECTIVE_CNT":DEFISNUL(model.certificateCnt),
                       @"IN_EFFECTIVE_CNT":DEFISNUL(model.notConformCnt),
                       @"FIT_RATE":DEFISNUL(model.fitRate),
                       @"CHECK_OPINION":DEFISNUL(model.checkOpinion),
                       @"EXTEND_INFO":@"",
                       @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"loginuser"),
                       @"CREATE_TIME":DEFISNUL([LSUtility nowTime]),
                       @"CREATE_IP":DEFISNUL([LSUtility getIPAddress]),
                       @"MODIFY_USER_NAME":@"",
                       @"MODIFY_TIME":@"",
                       @"MODIFY_IP":@"",
                       @"LOCAL_MODIFY_USER_NAME":@"",
                       @"LOCAL_MODIFY_TIME":@"",
                       @"LOCAL_MODIFY_STATE":@"ADD",
                       };
        
        BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:SAFE_SPECIAL_TYPE];
        if (isAdd) {
            NSLog(@"添加特种作业人员持证情况成功");
            
        } else {
            NSLog(@"添加特种作业人员持证情况失败");
        }
    }
    
    // 刷新安全列表页
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshSafeList" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma MARK - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMArr.count;
}

// 控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    return view;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 350;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 数据
    NSInteger section = indexPath.section;
    NSLog(@"%d", section);
    SafeSpecialTypeModel *model = self.dataMArr[section];

    SafeSpecialTypeCell *specialCell = [tableView dequeueReusableCellWithIdentifier:@"specialCell" forIndexPath:indexPath];
    specialCell.selectionStyle = UITableViewCellSelectionStyleNone;
    __weak __typeof(specialCell) weakCell = specialCell;

    specialCell.numberLabel.text = [NSString stringWithFormat:@"序号%d", section+1];
    
    // 删除
    specialCell.deleteBtn.tag = section;
    [specialCell.deleteBtn addTarget:self action:@selector(clickDelete:) forControlEvents:UIControlEventTouchUpInside];

    // 所属工种
    specialCell.workTypeBtn.tag = section;
    if (model.checkName) {
        [specialCell.workTypeBtn setTitle:model.checkName forState:UIControlStateNormal];
        
    } else {
        [specialCell.workTypeBtn setTitle:@"请选择工种" forState:UIControlStateNormal];
    }
    [specialCell.workTypeBtn addTarget:self action:@selector(selectWorkType:) forControlEvents:UIControlEventTouchUpInside];
    
    // 施工申报人数
    specialCell.filingsField.text = model.applyCnt;
    specialCell.filingsBlock = ^(NSString *str) {
        model.applyCnt = str;
        
        // 更新符合率
        if (model.applyCnt && ![model.applyCnt isEqualToString:@""] && model.certificateCnt && ![model.certificateCnt isEqualToString:@""]) {
            
            double rate = [model.certificateCnt doubleValue] / [model.applyCnt doubleValue];
            model.fitRate = [NSString stringWithFormat:@"%.2f", rate];
            NSString *str = [NSString stringWithFormat:@"%.2f%%", rate*100];
            weakCell.CoincidenceRateValue.text = DEFISNUL(str);
    
        }
    };
    
    // 核查实际人数
    specialCell.CheckNumberField.text = model.checkRealCnt;
    specialCell.checkNumberBlock = ^(NSString *str) {
        model.checkRealCnt = str;
    };
    
    // 有效证书人数
    specialCell.EffectiveNumberField.text = model.certificateCnt;
    specialCell.effectiveNumberBlock = ^(NSString *str) {
        model.certificateCnt = str;
        
        // 更新符合率
        if (model.applyCnt && ![model.applyCnt isEqualToString:@""] && model.certificateCnt && ![model.certificateCnt isEqualToString:@""]) {
            
            double rate = [model.certificateCnt doubleValue] / [model.applyCnt doubleValue];
            model.fitRate = [NSString stringWithFormat:@"%.2f", rate];
            NSString *str = [NSString stringWithFormat:@"%.2f%%", rate*100];
            weakCell.CoincidenceRateValue.text = DEFISNUL(str);
        }
    };
    
    // 不符合人数
    specialCell.nonconformityField.text = model.notConformCnt;
    specialCell.nonconformityBlock = ^(NSString *str) {
        model.notConformCnt = str;
    };
    
    // 符合率
    if (!model.fitRate) {
        model.fitRate = @"0";
    }
    double rate = [model.fitRate doubleValue];
    NSString *str = [NSString stringWithFormat:@"%.2f%%", rate*100];
    specialCell.CoincidenceRateValue.text = DEFISNUL(str);;

    // 检查意见/整改要求
    specialCell.CheckOpinionText.text = model.checkOpinion;
    specialCell.checkOpinionBlock = ^(NSString *str) {
        model.checkOpinion = str;
    };
    return specialCell;
}

// 删除
- (void)clickDelete:(UIButton *)deleteBtn {
    [self.dataMArr removeObjectAtIndex:deleteBtn.tag];
    [self.tableView reloadData];
}

// 选择工种
- (void)selectWorkType:(UIButton *)selectBtn {
    // 可选工种数据
    NSMutableArray *selectMArr = [[NSMutableArray alloc] initWithArray:self.workTypeArr];
    [self.dataMArr enumerateObjectsUsingBlock:^(SafeSpecialTypeModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([self.workTypeArr containsObject:obj.checkName]) {
            [selectMArr removeObject:obj.checkName];
        }
    }];
    SafeSpecialTypeModel *model = self.dataMArr[selectBtn.tag];
    if (model.checkName) {
        [selectMArr addObject:model.checkName];
    }
    NSNumber *ninit = [NSNumber numberWithInteger:0];

    [ActionSheetStringPicker showPickerWithTitle:nil rows:@[selectMArr] initialSelection:@[ninit] doneBlock:^(ActionSheetStringPicker *picker, NSArray *selectedIndex, NSArray *selectedValue) {
        
        // 修改数据
        [selectBtn setTitle:[selectedValue firstObject] forState:UIControlStateNormal];
        // 工种名称
        model.checkName = [selectedValue firstObject];
        
        // 工种类型
        if ([model.checkName isEqualToString:@"电工"]) {
            model.workType = @"WORK_TYPE_01";
            
        } else if ([model.checkName isEqualToString:@"电焊工"]) {
            model.workType = @"WORK_TYPE_02";
            
        } else if ([model.checkName isEqualToString:@"架子工"]) {
            model.workType = @"WORK_TYPE_03";
            
        } else if ([model.checkName isEqualToString:@"信号工"]) {
            model.workType = @"WORK_TYPE_04";
            
        } else if ([model.checkName isEqualToString:@"塔机司机"]) {
            model.workType = @"WORK_TYPE_05";
            
        } else if ([model.checkName isEqualToString:@"起重机司机"]) {
            model.workType = @"WORK_TYPE_06";
            
        } else if ([model.checkName isEqualToString:@"空压机司机"]) {
            model.workType = @"WORK_TYPE_07";
        }
    } cancelBlock:nil origin:self.view];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

//- (void)viewDidLayoutSubviews {
//    [super viewDidLayoutSubviews];
//    self.footerView.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 80);
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
